<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索框区域 row -->
      <el-row :gutter="20">
        <el-col :span="8">
          <div class="grid-content bg-purple">
            <el-input placeholder="请输入内容" class="input-with-select" v-model="queryInfo.query" clearable @clear="getUserList">
              <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="3">
          <div class="grid-content bg-purple">
            <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          </div>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList" stripe border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <!-- 操作区域 -->
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDialog(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUser(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showRoleDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 3, 5]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户弹出框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClose">
      <!-- 主体内容区域 -->
      <el-form :model="addUserForm" :rules="addUserRules" ref="userForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addUserForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addUserForm.password"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addUserForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addUserForm.email"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息弹出框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClose">
      <!-- 主体内容区域 -->
      <el-form :model="editUserForm" :rules="addUserRules" ref="editUserForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editUserForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editUserForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editUserForm.email"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 角色管理对话框 -->
    <el-dialog @close="roleDialogColse" title="分配角色" :visible.sync="roleDialogVisible" width="50%">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.role_name}}</p>
        <p>新分配的角色：
          <el-select v-model="checkedRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setRoleAllot">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import $http from '@/utils/resquest.js'
export default {
  data() {
    // 验证电话号的规则
    var checkmobile = (rule, value, callback) => {
      if (!value) return callback(new Error('请输入电话号'))
      var mr = /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/
      if (mr.test(value)) return callback()
      return callback(new Error('请输入正确的电话号'))
    }
    return {
      userList: [],
      // 总共数据条数
      total: 0,
      // 请求的数据
      queryInfo: {
        // 搜索参数
        query: '',
        // 当前页码值
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 2
      },
      // 控制添加对话框
      addDialogVisible: false,
      // 控制修改对话框
      editDialogVisible: false,
      // 添加用户表单
      addUserForm: {
        username: '',
        password: '',
        mobile: '',
        email: ''
      },
      // 用户表单
      editUserForm: {},
      // 表单验证规则
      addUserRules: {
        // 用户名
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 4, max: 10, message: '长度在 4 到 10 个字符', trigger: 'blur' }
        ],
        // 密码
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        // 电话
        mobile: [{ validator: checkmobile, trigger: 'blur' }],
        // 邮箱
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      },

      // 分配角色谈弹框
      roleDialogVisible: false,
      // 当前信息
      userInfo: {},
      // 被选中的角色的id
      checkedRoleId: '',
      // 角色列表
      rolesList: []
    }
  },
  methods: {
    // 添加用户
    addUser() {
      this.$refs.userForm.validate(async valid => {
        // console.log(valid)
        if (!valid) return this.$message.error('请填写完整的信息')
        const { data: res } = await $http.post('users', this.addUserForm)
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.addDialogVisible = false
        this.$message.success(res.meta.msg)
        this.getUserList()
      })
    },
    // 修改用户
    editUser() {
      this.$refs.editUserForm.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整且正确的信息')
        const { data: res } = await $http.put('users/' + this.editUserForm.id, {
          email: this.editUserForm.email,
          mobile: this.editUserForm.mobile
        })
        console.log(res)
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.editDialogVisible = false
        this.$message.success(res.meta.msg)
        this.getUserList()
      })
    },
    // 删除用户
    removeUser(id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { data: res } = await $http.delete(`users/${id}`)
          console.log(res)
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
          this.getUserList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 打开修改窗口
    async editDialog(id) {
      this.editDialogVisible = true
      console.log(id)
      const { data: res } = await $http.get(`users/${id}`)
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editUserForm = res.data
    },
    // 每页显示条数 pagesize,改变时
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // pagenum 页码值（当前页码值） 发生改变时
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.getUserList()
    },
    // 获取用户列表数据
    async getUserList() {
      const { data: res } = await $http.get('users', {
        params: this.queryInfo
      })
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 修改用户状态
    async userStateChange(row) {
      const { data: res } = await $http.put(`users/${row.id}/state/${row.mg_state}`)
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error('用户状态修改失败')
      }
      // 修改成功
      this.$message.success('用户状态修改成功！')
    },
    // 添加用户对话框关闭时重置数据
    addDialogClose() {
      this.$refs.userForm.resetFields()
    },
    editDialogClose() {
      this.$refs.editUserForm.resetFields()
    },

    // 分配角色
    async setRoleAllot() {
      if (!this.checkedRoleId) {
        this.roleDialogVisible = false
        return this.$message.error('请选择要分配的角色')
      }
      const { data: res } = await $http.put(`users/${this.userInfo.id}/role`, { rid: this.checkedRoleId })
      if (res.meta.status !== 200) {
        this.roleDialogVisible = false
        return this.$message.error('角色分配失败')
      }
      this.$message.success('角色分配成功')
      this.getUserList()
      this.roleDialogVisible = false
    },
    // 打开弹出框
    async showRoleDialog(row) {
      this.roleDialogVisible = true
      this.userInfo = {
        role_name: row.role_name,
        username: row.username,
        id: row.id
      }
      // 获取所有角色
      const { data: res } = await $http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('数据获取失败')
      // console.log(res.data)
      this.rolesList = res.data
      // this.getUserList()
    },
    // 关闭弹框重置数据
    roleDialogColse() {
      this.checkedRoleId = ''
      this.userInfo = []
    }
  },
  created() {
    this.getUserList()
  }
}
</script>
<style lang="less" scoped>
</style>